package com.kanshu.ksgb.fastread.doudou.module.personal.activity

import android.app.Activity
import android.content.Intent
import android.graphics.BitmapFactory
import android.media.ThumbnailUtils
import android.os.Bundle
import android.os.Parcelable
import android.provider.MediaStore
import android.support.design.widget.BottomSheetDialog
import android.text.Editable
import android.text.TextUtils
import android.view.LayoutInflater
import android.widget.TextView
import com.alibaba.android.arouter.facade.annotation.Route
import com.contrarywind.adapter.WheelAdapter
import com.contrarywind.view.WheelView
import com.kanshu.ksgb.fastread.doudou.R
import com.kanshu.ksgb.fastread.doudou.app.constants.ARouterConfig
import com.kanshu.ksgb.fastread.doudou.app.constants.Constants
import com.kanshu.ksgb.fastread.doudou.base.baseui.BaseActivity
import com.kanshu.ksgb.fastread.doudou.common.business.event.BindEvent
import com.kanshu.ksgb.fastread.doudou.common.business.utils.UserUtils
import com.kanshu.ksgb.fastread.doudou.common.net.bean.BaseResult
import com.kanshu.ksgb.fastread.doudou.common.net.retrofit.RetrofitHelper
import com.kanshu.ksgb.fastread.doudou.common.util.ARouterUtils
import com.kanshu.ksgb.fastread.doudou.common.util.StorageUtils
import com.kanshu.ksgb.fastread.doudou.common.util.ToastUtil
import com.kanshu.ksgb.fastread.doudou.common.util.Utils
import com.kanshu.ksgb.fastread.doudou.module.personal.bean.BindPhoneInfo
import com.kanshu.ksgb.fastread.doudou.module.personal.bean.UpdateInfoEvent
import com.kanshu.ksgb.fastread.doudou.module.personal.bean.UserData
import com.kanshu.ksgb.fastread.doudou.module.personal.listener.SoftKeyBoardListener
import com.kanshu.ksgb.fastread.doudou.module.personal.presenter.PersonCenterService
import io.reactivex.Observer
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.Disposable
import io.reactivex.schedulers.Schedulers
import kotlinx.android.synthetic.main.activity_user_info.*
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode

@Route(path = ARouterConfig.PERSONAL_USER_INFO)
class UserInfoActivity : BaseActivity(), SoftKeyBoardListener.OnSoftKeyBoardChangeListener {

    private val RESULT_LOAD_IMAGE = 99

    private var mSoftKeyListener: SoftKeyBoardListener? = null
    var userData:UserData? = null
    var currentCharacter = 0
    private val charastors = mutableListOf( "保密","男","女")

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_user_info)
        titlebarView.setTitle("我的资料")
        mSoftKeyListener = SoftKeyBoardListener(this)
        mSoftKeyListener!!.setOnSoftKeyBoardChangeListener(this)
        EventBus.getDefault().register(this)
        loadUserInfo()
        update_phone.setOnClickListener {
            if (userData != null && !TextUtils.isEmpty(userData?.phone)) {
                val info = BindPhoneInfo()
                info.nickname = userData?.nickname
                info.phone = userData?.phone
                info.rmb = Integer.valueOf(userData?.bind_phone_rmb)!!
                info.user_id = userData?.user_id
//                BindResultActivity.actionStart(activity!!, info)
                var map = HashMap<String, Parcelable>()
                map["data"] = info
                ARouterUtils.toActivity(ARouterConfig.PERSONAL_BIND_RESULT, map)
            } else {
                var map = HashMap<String, Integer>()
                map["type"] = Integer(BindPhoneActivity.BIND_PHONE)
                ARouterUtils.toActivity(ARouterConfig.PERSONAL_BIND_PHONE, map)
            }
        }
        txt_character.setOnClickListener { showCharacterSelector() }
        prentice.setOnClickListener { ARouterUtils.toActivity(ARouterConfig.PERSONAL_PRENTICE) }
    }


    private fun updateUserInfo(){
        val tmp = edit_nick_name.text.toString()
        if(!TextUtils.isEmpty(tmp) && !TextUtils.equals(tmp, userData?.nickname)){
            userData?.nickname = tmp
            updateInfo("nickname", tmp)
        }
    }


    override fun onActivityResult(requestCode: Int, resultCode:Int, data:Intent?) {
        super.onActivityResult(requestCode, resultCode, data);
        if(resultCode == RESULT_CANCELED ){
            return
        }

        if(requestCode == RESULT_LOAD_IMAGE && data!=null) {
            val worker = Schedulers.computation().createWorker();
            worker.schedule {
                val selectedImage = data.getData()
                val filePathColumn: Array<String> = arrayOf(MediaStore.Images.Media.DATA)
                val cursor = getContentResolver().query(selectedImage, filePathColumn, null, null, null)
                if (cursor.moveToFirst()) {
                    val columnIndex = cursor.getColumnIndex(filePathColumn[0])
                    val picturePath = cursor.getString(columnIndex)
                    cursor.close()
                    if (!TextUtils.isEmpty(picturePath)) {
                        val bmp = BitmapFactory.decodeFile(picturePath)
                        val thumbNail = ThumbnailUtils.extractThumbnail(bmp, 240, 240)
                        AndroidSchedulers.mainThread().scheduleDirect {
                            head_view.setImageBitmap(thumbNail)
                        }
                        bmp.recycle()
                        val  img_url = Utils.bitmapToBase64(thumbNail)
                        updateInfo("headimgurl",img_url)
                    }
                }
            }
        }
    }

    private fun updateInfo(key:String ,value:String?){
        val params = mutableMapOf<String, String?>()
        params.put(key,value)
        val helper = RetrofitHelper.getInstance()
        helper.createService(PersonCenterService::class.java)
                .modifyUserBaseInfo(params)
                .compose(asyncRequest())
                .subscribe(object : Observer<BaseResult<String>> {
                    override fun onComplete() {
                    }

                    override fun onSubscribe(d: Disposable?) {
                    }

                    override fun onNext(t: BaseResult<String>?) {
                        t?.result?.status?.run {
                            ToastUtil.showMessage(if(code == 0) "更新成功" else "更新失败: $msg")
                            EventBus.getDefault().post(UpdateInfoEvent())
                        }
                    }

                    override fun onError(e: Throwable?) {
                        e?.printStackTrace()
                        ToastUtil.showMessage("更新失败")
                    }
                })
    }

    private fun loadUserInfo(){
        val helper = RetrofitHelper.getInstance()
        val paramsMap = mutableMapOf<String, String>()
        paramsMap.put("get_master_info","1")
        paramsMap.put("get_account_info","1")
        paramsMap.put("get_phone_info","1")
        helper.createService(PersonCenterService::class.java)
                .getUserBaseInfo(paramsMap )
                .compose(asyncRequest())
                .subscribe(object : Observer<BaseResult<UserData>> {
                    override fun onComplete() {
                    }

                    override fun onSubscribe(d: Disposable?) {
                    }

                    override fun onNext(t: BaseResult<UserData>?) {
                        t?.result?.data?.apply {
                            initUserInfoView(this)
                            StorageUtils.setPreference<String>(activity, Constants.SP_NAME, Constants.USER_BIND_PHONE + t.result.data.user_id, t.result.data.phone)
                        }
                    }

                    override fun onError(e: Throwable?) {
                        e?.printStackTrace()
                    }
                })
    }

    private fun initUserInfoView(data: UserData?){
        this.userData = data
        if(userData != null){
            if(!TextUtils.isEmpty(userData?.phone)){
                update_phone.text = Utils.securityShowPhone(userData?.phone)
                update_phone.setTextColor(resources.getColor(R.color.pay_desc))
            }
            val regex = Regex("^[0-9]{3,3}[x]{4,4}[0-9]{4,4}$")
            if(!TextUtils.isEmpty(userData?.nickname) && userData?.nickname.toString().matches(regex)){
                edit_nick_name.hint = Editable.Factory.getInstance().newEditable(userData?.nickname)
                edit_nick_name.text = Editable.Factory.getInstance().newEditable("")
            }else {
                edit_nick_name.text = Editable.Factory.getInstance().newEditable(userData?.nickname)

            }
            userData?.master_info?.apply {
                master_name.text = Editable.Factory.getInstance().newEditable(nickname)
            }
            reg_time.text = Editable.Factory.getInstance().newEditable(userData?.reg_time)
            val character = charastors[userData?.sex?.toInt()?: 0]
            txt_character.text =  Editable.Factory.getInstance().newEditable(character)
            currentCharacter = userData?.sex?.toInt()?:0
            head_view.setImageResource(getUserHead(currentCharacter))
        }
    }

    private fun showCharacterSelector(){
        val dialog = BottomSheetDialog(this)
        val view = LayoutInflater.from(this)?.inflate(R.layout.layout_dialog_charater_selector, null)
        dialog.setContentView(view)
        val btn_cancel : TextView = view?.findViewById(R.id.btn_cancel) as TextView
        val btn_submit : TextView = view.findViewById(R.id.btn_submit) as TextView
        val wheelPicker  = view.findViewById(R.id.wheelview) as WheelView
        wheelPicker.setCyclic(false)
        wheelPicker.adapter =ArrayWheelAdapter (charastors)
        btn_cancel.setOnClickListener { dialog.dismiss() }
        btn_submit.setOnClickListener { dialog.dismiss()
            val position = wheelPicker.currentItem
            val character = charastors[position]
            txt_character.text =  Editable.Factory.getInstance().newEditable(character)
            currentCharacter= position
            head_view.setImageResource(getUserHead(position))
            updateInfo("sex", position.toString())

        }
        wheelPicker.currentItem = currentCharacter
        dialog.setCanceledOnTouchOutside(false)
        dialog.setCancelable(false)
        dialog.show()
    }

    override fun keyBoardShow(height: Int) {
        edit_nick_name.hint = ""
    }

    override fun keyBoardHide(height: Int) {
        updateUserInfo()
    }

   @Subscribe(threadMode = ThreadMode.MAIN)
    fun handleBindEvent(bindEvent: BindEvent) {
        if (bindEvent.code == BindEvent.SUCCESS) {
            val mPhone = StorageUtils.getPreference(this@UserInfoActivity, Constants.SP_NAME, Constants.USER_BIND_PHONE + UserUtils.getUserId(), "")
            update_phone.text = Utils.securityShowPhone(mPhone)
        }
    }

    companion object {
        @JvmStatic
        fun actionStart(activity: Activity){
            activity.startActivity(Intent(activity,UserInfoActivity::class.java))
        }
        @JvmStatic
        fun getUserHead(character:Int) = when(character){
            1-> R.mipmap.ic_edit_head_male
            2-> R.mipmap.ic_edit_head_female
            else-> R.mipmap.ic_edit_head_unknow
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        EventBus.getDefault().unregister(this)
        mSoftKeyListener!!.detachView()
    }

}

class ArrayWheelAdapter(val datas: MutableList<String>):WheelAdapter<String>{
    override fun indexOf(o: String?) = datas.indexOf(o)

    override fun getItemsCount() = datas.size

    override fun getItem(index: Int) = datas[index]

}
